package vn.pyco.prez.tapestry.model;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.tapestry5.tree.TreeModelAdapter;

import vn.pyco.prez.util.StringListUtils;

public class FileTreeModelAdapter implements TreeModelAdapter<File> {
	
	private IOFileFilter _filter;
	
	public FileTreeModelAdapter() {
		_filter = null;
	}
	
	public FileTreeModelAdapter(List<String> filterExt) {
		_filter = new SuffixFileFilter(filterExt, IOCase.INSENSITIVE);
	}

	public FileTreeModelAdapter(String filterExt) {
		_filter = new SuffixFileFilter(StringListUtils.stringToList(filterExt), IOCase.INSENSITIVE);
	}

	@Override
	public boolean isLeaf(File value) {
		return value.isFile();
	}

	@Override
	public boolean hasChildren(File value) {
		return (value.isDirectory() && !getChildren(value).isEmpty());
	}

	@Override
	public List<File> getChildren(File value) {
		List<File> result = new ArrayList<File>();

		File[] dirChildren = value.listFiles((FileFilter)DirectoryFileFilter.DIRECTORY);
		File[] fileChildren = value.listFiles((FileFilter)_filter);
		
		if(dirChildren != null){
			result.addAll(Arrays.asList(dirChildren));
		}
		
		if(fileChildren != null){
			result.addAll(Arrays.asList(fileChildren));
		}
		
		return result;
	}

	@Override
	public String getLabel(File value) {
		String label = value.getName();
		if(label == null || label.isEmpty()) {
			label = value.getPath();
		}
		return label;
	}

}
